<script setup lang="ts">
import { ref, watch } from "vue";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import type { Role } from "@/api/role";
import { createRole, updateRole } from "@/api/role";

const props = defineProps<{
  visible: boolean;
  role?: Partial<Role>;
  type: "add" | "edit";
}>();

const emit = defineEmits<{
  (e: "update:visible", value: boolean): void;
  (e: "save"): void;
}>();

const formRef = ref<FormInstance>();
const loading = ref(false);

const formData = ref({
  name: "",
  code: "",
  description: "",
  status: 1
});

const rules: FormRules = {
  name: [
    { required: true, message: "请输入角色名称", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
  ],
  code: [
    { required: true, message: "请输入角色编码", trigger: "blur" },
  ],
  description: [
    { max: 200, message: "长度不能超过 200 个字符", trigger: "blur" }
  ]
};

// 监听visible变化，重置表单
watch(() => props.visible, (val) => {
  if (val) {
    formData.value = {
      name: props.role?.name || "",
      code: props.role?.code || "",
      description: props.role?.description || "",
      status: props.role?.status ?? 1
    };
  } else {
    formRef.value?.resetFields();
  }
});

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        const api = props.type === "add" ? createRole : updateRole;
        const data = props.type === "add"
          ? formData.value
          : { ...formData.value, id: props.role?.id };

        const res = await api(data);
        if (res.code === 0) {
          ElMessage.success(props.type === "add" ? "添加成功" : "编辑成功");
          emit("update:visible", false);
          emit("save");
        } else {
          ElMessage.error(res.msg || (props.type === "add" ? "添加失败" : "编辑失败"));
        }
      } catch (error) {
        console.error(props.type === "add" ? "添加角色出错:" : "编辑角色出错:", error);
        ElMessage.error(props.type === "add" ? "添加失败" : "编辑失败");
      } finally {
        loading.value = false;
      }
    }
  });
};

// 取消
const handleCancel = () => {
  emit("update:visible", false);
};
</script>

<template>
  <el-dialog :model-value="visible" @update:model-value="(val) => emit('update:visible', val)"
    :title="type === 'add' ? '添加角色' : '编辑角色'" width="500px" @close="handleCancel">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入角色名称" />
      </el-form-item>
      <el-form-item label="角色编码" prop="code">
        <el-input v-model="formData.code" placeholder="请输入角色编码" :disabled="props.role?.is_system === 1" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入角色描述" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>